from .models import *
from rest_framework import serializers
from django.contrib.auth.models import User
import datetime


class TodoItemSerializer(serializers.HyperlinkedModelSerializer):
    task_id = serializers.IntegerField(source="todo_task.id")

    class Meta:
        model = TodoItem
        fields = ["content", "is_done", "task_id", "id"]
        read_only_fields = ('id',)

    def create(self, validated_data):
        todo_task_id = validated_data['todo_task']['id']
        todo_task = TodoTask.objects.get(id=todo_task_id)
        validated_data['todo_task'] = todo_task

        instance = TodoItem.objects.create(**validated_data)
        return instance

    def update(self, instance, validated_data):
        item = TodoItem.objects.get(id=instance.id)
        item.is_done = validated_data['is_done']
        item.save()
        return item


class TodoTaskSerializer(serializers.ModelSerializer):
    items = TodoItemSerializer(source="todoitem_set", many=True, required=False)

    class Meta:
        model = TodoTask
        fields = ['task_name', 'id', "items"]
        read_only_fields = ('id', 'author')


class TodoCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = TodoCategory
        fields = ['name', 'id']


class TaskInCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = TaskInCategory
        fields = ['task', 'category']


class ShareLinkSerializer(serializers.ModelSerializer):
    task_id = serializers.IntegerField(source = "task.id")

    class Meta:
        model = ShareLink
        fields = ["task_id", "expires_after"]
        read_only_fields = ["expires_at", "create_at", "task"]
    